package com.singfan.core.dao.database.impl;

import com.singfan.common.db.DaoBaseGeneric;
import com.singfan.common.db.DbContext;
import com.singfan.common.db.LongResultSetReader;
import com.singfan.common.db.PrimaryKeyBuilder;
import com.singfan.core.dao.database.ICustomerDao;
import com.singfan.core.dao.database.model.Customer;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 *
 * Author: hansonghe
 * Date: 2015-08-19 12:12
 * Desc:
 */
@Repository
public class CustomerDaoImpl extends DaoBaseGeneric<Customer> implements ICustomerDao {
    @Override
    protected String getTableName(Object hashKey) {
        return tableNameBase;
    }

    @Override
    protected String getDatabaseId(Object hashKey) {
        return "app_1";
    }


    @Override
    public Customer findCustomer(long customerId) {
        return selectByPK(customerId, customerId);
    }

    @Override
    public Customer findCustomerByPhoneNumber(String phoneNumber) {
        String sql = "SELECT * FROM " + getTableName(phoneNumber) + " WHERE phone_number=?";

        return selectOne(phoneNumber, sql, phoneNumber);
    }

    @Override
    public void createCustomer(Customer customer) {
        long customerId = PrimaryKeyBuilder.getInstance().build(DbContext.getDbConfigProvider().getTable(tableNameBase).getId(), getTableNewestVersion());
        customer.setId(customerId);
        insert(customer.getId(), customer);
    }

    @Override
    public void updatePhoneTypeAndCityId(long customerId, String phoneType, int cityId) {
        String sql = "UPDATE " + getTableName(customerId) + " SET phone_type=?,city_id=? WHERE id=?";
        execute(customerId, sql, phoneType, cityId, customerId);
    }

    @Override
    public void update(Customer customer) {
        updateByPK(null, customer);
    }

    @Override
    public List<Long> selectAllCustomerIdList() {
        String sql = "SELECT id FROM " + getTableName(null);
        return (List<Long>)executeQuery(null, sql, null, new LongResultSetReader());
    }

    @Override
    public boolean isDisabledAccount(String phoneNumber) {
        String sql = "SELECT * FROM " + getTableName(phoneNumber) + " WHERE phone_number=? AND status=3";
        return isExist(null, sql, phoneNumber);
    }

    @Override
    public void updateCustomerStatus(long customerId, int status) {
        String sql = "UPDATE " + getTableName(customerId) + " SET status=? WHERE id=?";
        execute(customerId, sql, status, customerId);
    }
}
